<!--
 * @Author: quit
 * @Date: 2021-12-08 10:37:09
 * @LastEditTime: 2021-12-11 15:46:45
 * @Descripttion: 类型状态管理
-->
<template>
  <div id="SubDrandItem">
    <div class="app-container" style="height: 100%">
      <el-row :gutter="5">
        <!-- 左侧 -->
        <el-col :span="4" class="left">
          <el-card>
            <div v-loading="treeLoading" class="item-box">
              <el-input v-model="filterText" class="tree-search" placeholder="输入关键字进行过滤" />
              <el-tree ref="tree" :data="treeData" :props="defaultProps" :filter-node-method="filterNode" @node-click="handleNodeClick" />
            </div>
          </el-card>
        </el-col>
        <!-- 右侧 -->
        <el-col :span="20" class="right">
          <el-card>
            <el-row class="right-container">
              <el-col>
                <el-divider content-position="left">搜索信息</el-divider>
                <div class="search">
                  <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
                    <el-form-item :label="'类型'">
                      <el-input v-model="searchFrom.subsysname" disabled :placeholder="'请选择类型名'" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-refresh-right" @click="refresh">{{ '重置' }}</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
              <el-col class="btns">
                <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemsBtn">{{ '添加类型状态' }}</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button>
              </el-col>
              <el-col>
                <el-table
                  ref="table"
                  v-loading="loading"
                  :max-height="maxHeight"
                  :data="tableData"
                  :empty-text="$t('table.emptyText')"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" min-width="40" fixed="left" />
                  <el-table-column prop="id" label="ID" min-width="80" fixed="left" />
                  <el-table-column prop="subsystemid" :label="'类型ID'" min-width="80" fixed="left" />
                  <el-table-column prop="statetype" :label="'设备状态类型'" min-width="160">
                    <template slot-scope="scope">
                      <div class="statetype-show">
                        <span v-if="scope.row.statetype === 1">运行状态</span>
                        <span v-if="scope.row.statetype === 2">报警状态</span>
                        <span v-if="scope.row.statetype === 3">故障</span>
                        <span v-if="scope.row.statetype === 4">通讯</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="showicon" :label="'显示图标'" min-width="80" />
                  <el-table-column :label="'图标预览'" min-width="80">
                    <template slot-scope="scope">
                      <div class="img-box">
                        <img :src="`${imgBaseURL}/image/icon/${iconPath}/${scope.row.showicon}`">
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="min" :label="'最小值'" min-width="80" />
                  <el-table-column prop="max" :label="'最大值'" min-width="80" />
                  <el-table-column prop="andor" :label="'条件异或'" min-width="100" />
                  <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="200">
                    <template slot-scope="scope">
                      <el-button type="warning" size="mini" @click="handleEdit(scope.row)">{{ $t('button.edit') }}</el-button>
                      <el-button type="danger" size="mini" @click="handleDetele(scope.row)">{{ $t('button.delete') }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination
                  :current-page="pages.page"
                  :page-sizes="[1, 5, 10, 15]"
                  :page-size="pages.size"
                  layout="prev, pager, next, total, sizes, jumper"
                  :total="pages.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 添加\修改弹出层 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" @close="addDialogClose">
      <div class="add-dialog-container">
        <el-form ref="addFrom" :model="addDialogForm" label-width="80px">
          <el-form-item label="设备类型">
            <el-input v-model="searchFrom.subsysname" disabled />
          </el-form-item>
          <el-form-item label="状态类型">
            <el-select v-model="addDialogForm.statetype" placeholder="请选择状态类型" clearable>
              <el-option v-for="(item, index) in stateTypeData" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型编号">
            <el-select v-model="addDialogForm.subsysmodeid" placeholder="请选择类型编号" clearable>
              <el-option v-for="(item, index) in subsysmodeidData" :key="index" :label="item.mitemname" :value="item.subsysmodeid" />
            </el-select>
          </el-form-item>
          <el-form-item label="最小值">
            <el-input v-model="addDialogForm.min" placeholder="请输入最小值" />
          </el-form-item>
          <el-form-item label="最大值">
            <el-input v-model="addDialogForm.max" placeholder="请输入最大值" />
          </el-form-item>
          <el-form-item label="条件异或">
            <el-select v-model="addDialogForm.andor" placeholder="请选择条件类型" clearable>
              <el-option v-for="(item, index) in andorData" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="图标显示">
            <el-select v-model="addDialogForm.showicon" placeholder="请选择显示图标" clearable>
              <el-option v-for="(item, index) in isShowData" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="addDialogState === 0" type="primary" @click="sendAddItem">确 定</el-button>
        <el-button v-if="addDialogState === 1" type="primary" @click="sendEditItem">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import { getData } from '@/utils/auth'
import { mapGetters } from 'vuex'
import { getSubStateList, getSysModeList, addSubStateItem, editSubStateItem, deleteSubStateItem } from '@/api/BotRequest'
import { getSubSysInfo } from '@/api/BmRequest'

export default {
  components: {},
  data() {
    return {
      botData: {},
      treeData: [],
      filterText: '',
      treeLoading: false,
      defaultProps: {
        children: 'children',
        label: 'subsysname'
      },
      searchFrom: {
        subsysname: null,
        subsystemid: null
      },
      iconPath: null,
      maxHeight: null,
      loading: false,
      isCheckedArr: [],
      tableData: [],
      pages: {
        page: 1,
        size: 10,
        total: 0
      },
      dialogTitle: '',
      addDialogState: null,
      dialogVisible: false,
      addDialogForm: {
        id: null,
        appid: null,
        subsystemid: null,
        statetype: null,
        subsysmodeid: null,
        min: null,
        max: null,
        andor: null,
        showicon: null
      },
      stateTypeData: [
        { label: '未选择', value: 0 },
        { label: '运行状态', value: 1 },
        { label: '报警状态', value: 2 },
        { label: '故障', value: 3 },
        { label: '通讯', value: 4 }
      ],
      subsysmodeidData: [],
      andorData: [
        { label: 'and', value: 0 },
        { label: 'or', value: 1 }
      ],
      isShowData: [
        { label: '停止', value: 'stop.png' },
        { label: '运行', value: 'run.gif' },
        { label: '报警', value: 'alarm.png' },
        { label: '故障', value: 'fault.png' }
      ]
    }
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapGetters(['imgBaseURL'])
  },
  // 监控data中的数据变化
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.botData = getData('BotData')
    this.getSubSysInfo()
    // this.getSubStateList()
  }, // 生命周期 - 创建完成（可以访问当前this实例）
  mounted() {
    this.setTableHeight()
    window.onresize = () => {
      this.setTableHeight()
    }
  }, // 生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 动态设置表格高
    setTableHeight() {
      let num = $('.right-container').height() - 203
      this.maxHeight = num
    },
    // 表头颜色
    // tableHeaderColor() {
    //   return 'padding:5px 0;background-color:#f2f2f2;font-wight:400'
    // },
    /* 左侧树形数据操作 */
    // 获取类型列表
    async getSubSysInfo() {
      this.treeLoading = true
      try {
        const { data } = await getSubSysInfo()
        this.treeData = data
      } catch (error) {
        console.log(error)
      } finally {
        this.treeLoading = false
      }
    },
    // 搜索事件
    filterNode(value, data) {
      if (!value) return true
      if (data.children) return false
      return data.subsysname.indexOf(value) !== -1
    },
    // 展开或折叠
    // setAllExpand(state) {
    //   var nodes = this.$refs.tree.store.nodesMap
    //   for (var i in nodes) {
    //     nodes[i].expanded = state
    //   }
    // },
    // 节点点击事件
    handleNodeClick(data) {
      if (data.subsysparent !== -1) {
        this.iconPath = data.subsysicon
        this.searchFrom.subsysname = data.subsysname
        this.searchFrom.subsystemid = data.subsystemid
        this.getSubStateList()
      }
    },

    /* 右侧列表操作 */
    // 获取设备数据列表
    async getSubStateList() {
      const obj = {
        submodedranditem: {
          appid: this.botData.id,
          subsystemid: this.searchFrom.subsystemid
        },
        pages: {
          page: this.pages.page,
          size: this.pages.size
        }
      }
      try {
        this.loading = true
        const { data } = await getSubStateList(obj)
        this.tableData = data.records
        this.pages.page = data.current
        this.pages.size = data.size
        this.pages.total = data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    // 获取阈值数据

    // 重置按钮
    refresh() {
      this.searchFrom.subsystemid = null
      this.searchFrom.subsysname = null
      this.iconPath = null
      this.getSubStateList()
    },

    // 添加按钮
    async addItemsBtn() {
      if (!this.searchFrom.subsysname) {
        this.$message.warning('请先选着需要添加的类型!')
      } else {
        this.addDialogForm.appid = this.botData.id
        this.addDialogForm.subsystemid = this.searchFrom.subsystemid
        this.addDialogState = 0
        this.dialogTitle = '添加类型状态'
        const submodemanager = {
          subsystemid: this.addDialogForm.subsystemid,
          appid: this.addDialogForm.appid
        }
        const { data } = await getSysModeList(submodemanager)
        this.subsysmodeidData = data
        this.dialogVisible = true
      }
    },

    /* table选择事件 */
    handleSelectionChange(val) {
      let nowArr = []
      console.log(val)
      val.forEach(item => {
        nowArr.push(item.id)
      })
      this.isCheckedArr = nowArr
    },

    // 批量删除
    async batchRemove() {
      if (this.isCheckedArr.length > 0) {
        this.$confirm('此操作将删除所选项目, 是否继续?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            if (this.isCheckedArr.length === this.tableData.length) {
              if (this.pages.page > 1) {
                this.pages.page--
              } else {
                this.pages.page = 1
              }
            }
            const { message } = await deleteSubStateItem(this.isCheckedArr)
            await this.getSubStateList()
            this.$message.success({ message })
          })
          .catch(error => {
            console.log(error)
            this.$refs.table.clearSelection()
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },

    /* 弹出框事件 */
    // 关闭
    addDialogClose() {
      this.addDialogForm = {
        appid: null,
        subsystemid: null,
        mitemname: null,
        mitemdatatype: null,
        mitemreadorwrite: null,
        mitemnum: null,
        mitemnumdescribe: null,
        mitemlevel: null,
        miteminitvalue: null,
        thresholdid: null,
        mitemtime: null,
        mitemunit: null,
        mitemishistory: null,
        mitemisenergy: null,
        mitemisalarm: null,
        mitemmaths: null,
        subsysalarmlevel: null,
        subsysalarmdescribe: null,
        subsysalarmtype: null,
        subsysalarmonoff: null,
        subsysalarmdeviation: null,
        subsysalarmdeviationinitvalue: null,
        subsysalarmminimini: null,
        subsysalarmmini: null,
        subsysalarmmax: null,
        subsysalarmmaxmax: null,
        subsysalarmsleep: null,
        subsysalarmcss: null,
        subsysalarmsort: null
      }
      this.dialogTitle = ''
    },
    // 确定
    async sendAddItem() {
      try {
        const { message } = await addSubStateItem(this.addDialogForm)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        if (this.tableData.length === this.pages.size) {
          this.pages.page++
        }
        this.getSubStateList()
        this.dialogVisible = false
      }
    },
    // 提交
    async sendEditItem() {
      const submodedranditem = { ...this.addDialogForm }
      try {
        const { message } = await editSubStateItem(submodedranditem)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        this.getSubStateList()
        this.dialogVisible = false
      }
    },

    /* tabel-item 操作 */
    // 编辑
    async handleEdit(data) {
      this.addDialogForm = { ...data }
      this.addDialogState = 1
      this.dialogTitle = '编辑类型状态'
      const submodemanager = {
        subsystemid: this.addDialogForm.subsystemid,
        appid: this.addDialogForm.appid
      }
      const res = await getSysModeList(submodemanager)
      if (res.data.length < 1) {
        res.data.unshift({ mitemname: '无数据', subsysmodeid: 0 })
        this.subsysmodeidData = res.data
      } else {
        this.subsysmodeidData = res.data
      }
      this.dialogVisible = true
    },
    // 删除
    handleDetele(data) {
      this.$confirm('此操作将删除当前项目, 是否继续?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const ids = [data.id]
          const { message } = await deleteSubStateItem(ids)
          if (this.tableData.length === 1) {
            if (this.pages.page > 1) {
              this.pages.page--
            } else {
              this.pages.page = 1
            }
          }
          await this.getSubStateList()
          this.$message.success({ message })
        })
        .catch(error => {
          console.log(error)
        })
    },

    /* 分页操作 */
    // 分页当前页切换
    async handleCurrentChange(newPage) {
      this.pages.page = newPage
      await this.getSubStateList()
    },
    // 分页显示条数切换
    async handleSizeChange(newSize) {
      this.pages.size = newSize
      await this.getSubStateList()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 15px 20px;
}
::v-deep .el-divider {
  margin: 14px 0 !important;
}

#SubDrandItem {
  .app-container {
    .left {
      .item-box {
        height: calc(100vh - 92px);
        overflow: auto;
        .tree-search {
          margin-bottom: 10px;
        }
      }
    }
    .right {
      .right-container {
        height: calc(100vh - 92px);
        .search {
          border: 1px solid #dcdfe6;
          border-top: none;
          padding: 34px 10px 10px 10px;
          margin-top: -14px;
          .el-input {
            width: 240px;
          }
          .el-button {
            margin-left: 20px;
          }
        }
        .btns {
          padding: 10px 0;
        }
        .img-box {
          width: 40px;
          img {
            width: 100%;
          }
        }
      }
    }
  }
  .add-dialog-container {
    .el-input,
    .el-select {
      width: calc(100% - 10px);
    }
  }
}
</style>
